package com.zenithsun.common.security.csrf;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.*;
import java.io.IOException;

/**
 * HTML form without CSRF protection 漏洞处理标签
 * @author Jiang
 */
public class TokenTagForForm extends SimpleTagSupport {

    /**
     * 生成CSRF token Tag
     * @throws JspException
     * @throws IOException
     */
    @Override
    public void doTag() throws JspException, IOException {
        PageContext ctx = (PageContext) getJspContext();
        String token = CSRFTokenManager.createToken();
        // CSRF token for session
        ctx.getSession().setAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME,token);
        JspWriter out = ctx.getOut();
        // CSRF token for form
        out.print("<input type=\"hidden\" name=\"" + CSRFTokenManager.CSRF_TOKEN_FOR_FORM_PARAM_NAME+"\" id=\"" + CSRFTokenManager.CSRF_TOKEN_FOR_FORM_PARAM_NAME+"\" value=\""+token+"\">");
    }
}
